package com.weicong.openchat.fragment;

import java.util.ArrayList;

import org.jivesoftware.smack.util.StringUtils;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.appkefu.lib.interfaces.KFIMInterfaces;
import com.appkefu.lib.service.KFMainService;
import com.appkefu.lib.ui.entity.KFRosterEntity;
import com.appkefu.lib.utils.KFImageUtils;
import com.appkefu.lib.xmpp.XmppFriend;
import com.appkefu.lib.xmpp.XmppVCard;
import com.weicong.openchat.R;
import com.weicong.openchat.activity.ProfileFriendActivity;
import com.weicong.openchat.activity.RobotChatActivity;
import com.ypy.eventbus.EventBus;

public class RosterListFragment extends Fragment {
	
	private ListView mListView;
	private ArrayList<KFRosterEntity> mRosterEntity = new ArrayList<KFRosterEntity>();
	private RosterAdapter mRosterAdapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		EventBus.getDefault().register(this);
		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		View v = inflater.inflate(R.layout.fragment_roster_list, null);
		
		mListView = (ListView) v.findViewById(R.id.roster_listView);
		TextView emptyView = new TextView(getActivity());  
		emptyView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));  
		emptyView.setText("ͨѶ¼Ϊ��");
		emptyView.setTextColor(getActivity().getResources().getColor(R.color.text_color));
		emptyView.setGravity(Gravity.CENTER);  
		emptyView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		emptyView.setVisibility(View.GONE);  
		((ViewGroup)mListView.getParent()).addView(emptyView);  
		mListView.setEmptyView(emptyView);
		View headerView = inflater.inflate(R.layout.robot_chat_item, null);
		mListView.addHeaderView(headerView);
		mRosterAdapter = new RosterAdapter(mRosterEntity);
		mListView.setAdapter(mRosterAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				
				if (position == 0) {
					Intent intent = new Intent(getActivity(), RobotChatActivity.class);
					startActivity(intent);
				} else {
					String username = StringUtils.parseName(mRosterEntity.get(position-1).getJid());
					Intent intent = new Intent(getActivity(), ProfileFriendActivity.class);
					intent.putExtra(ProfileFriendActivity.USERNAME, username);
					startActivity(intent);
				}
			}
		});
		
		return v;
	}
	
	@Override
	public void onStart() {
		super.onStart();
		
		//��������״̬�仯���
		IntentFilter intentFilter = new IntentFilter(KFMainService.ACTION_XMPP_PRESENCE_CHANGED);
        getActivity().registerReceiver(mXmppreceiver, intentFilter); 

	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		//���ͻ�ȡȫ����������
		KFIMInterfaces.getFriends(getActivity());
		
		//�����ڸ���ǩ��
		//String status = KFIMInterfaces.getStatus(username);
		//����:0; �뿪: 1; æ: 3; ����: 5;
		//int state = KFIMInterfaces.getPresenceState(username);
	}
	
	@Override
	public void onStop() {
		super.onStop();

        getActivity().unregisterReceiver(mXmppreceiver);
	}
	
	private class RosterAdapter extends ArrayAdapter<KFRosterEntity> {
		
		public RosterAdapter(ArrayList<KFRosterEntity> rosters) {
			super(getActivity(), 0, rosters);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				convertView = getActivity().getLayoutInflater().inflate(R.layout.roster_list_item, null);
				viewHolder = new ViewHolder();
				viewHolder.head = (ImageView) convertView.findViewById(R.id.iv_head);
				viewHolder.name = (TextView) convertView.findViewById(R.id.tv_nickname);
				
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			
			KFRosterEntity entity = getItem(position);
			
			viewHolder.head.setImageResource(R.drawable.head);
			String username = StringUtils.parseName(entity.getJid());
			String nickname = KFIMInterfaces.getOtherNickname(username);
			if(nickname == null) {
				nickname = username;
			}
			viewHolder.name.setText(nickname);
			
			//���öԷ���ͷ��
			updateVCardThread(username, viewHolder.head);
			
			return convertView;
		}
	}
	
	private class ViewHolder {
		public ImageView head;
		public TextView name;
	}
	
	private BroadcastReceiver mXmppreceiver = new BroadcastReceiver() {
		
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(KFMainService.ACTION_XMPP_PRESENCE_CHANGED)) {
            	
            	//����״̬��Ӧ��ϵ��0:����; 1:�뿪; 2:�뿪; 3:æ; 4:��ӭ����; 5:����;
                int stateInt = intent.getIntExtra("state", XmppFriend.OFFLINE);//����״̬��Ĭ��Ϊ����
                
                String userId = intent.getStringExtra("userid"); //�û���jid
                String name = intent.getStringExtra("name"); //�ǳ�
                String status = intent.getStringExtra("status"); //����ǩ��
                
                if(StringUtils.parseName(userId).length() > 0) {
            		KFRosterEntity entity = new KFRosterEntity();
            		entity.setJid(userId);
            		entity.setNick(name);
            		if(!mRosterEntity.contains(entity)) {
            			mRosterEntity.add(entity);               		
            		} 
            		
            		mRosterAdapter.notifyDataSetChanged();
                }
            }            
        }
    };
    
    @SuppressLint("HandlerLeak")
	private void updateVCardThread(final String username, final ImageView avatar) {
		
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if(msg.what == 1) {
					String avatarPath = (String)msg.obj;
					Bitmap bitmap = KFImageUtils.getBitmapByPath(avatarPath);
					if(bitmap != null)
						avatar.setImageBitmap(bitmap);
					else
						avatar.setImageResource(R.drawable.head);
				}
				
			}
		};
		
		new Thread() {
			public void run() {
				Message msg = new Message();			
				
				//��ȡͷ���ַ
				String avatarPath = XmppVCard.getOthersAvatarPath(username);
		
				msg.what = 1; 
				msg.obj = avatarPath; 
								
				handler.sendMessage(msg);
			}
		}.start();
		
	}
    
    public void onEventMainThread(Event event) {  
		String username = event.getUsername();
		KFRosterEntity entity;
		for (int i = 0; i < mRosterEntity.size(); i++) {
			entity = mRosterEntity.get(i);
			if (StringUtils.parseName(entity.getJid()).equals(username)) {
				mRosterEntity.remove(i);
				mRosterAdapter.notifyDataSetChanged();
				break;
			}
		}
		
	}
    
    public static class Event {
    	public String mUsername;
    	
    	public Event(String username) {
    		mUsername = username;
    	}
    	
    	public String getUsername() {
    		return mUsername;
    	}
    }

}
